package test.stat;



import dm.ast.DmASTNode;
import test.log.SqlLog;
import test.utility.SqlRun;
import test.utility.Utility;

import java.util.ArrayList;
import java.util.List;

public class StatExecTime extends Statictics {
    //记录时间统计信息单元
    class TimeTuple implements Comparable<TimeTuple> {
        String sql = null;
        long time = -1l;

        public TimeTuple(String sql, long time) {
            this.sql = sql;
            this.time = time;
        }

        @Override
        public int compareTo(TimeTuple o) { //需要根据执行时间降序排列
            if (time > o.time) {
                return -1;
            } else if (time == o.time) {
                return 0;
            } else {
                return 1;
            }
        }
    }

    //保留SQL数目
    public static int TOP_NUM = 20;
    //有序， 按照执行时间从大到小排列
    public ArrayList<TimeTuple> timeStats = new ArrayList<TimeTuple>();

    //添加一个SQL统计信息
    @Override
    public void addSQLStat(String sql, SqlRun run) {
        timeStats.add(new TimeTuple(sql, run.getExecTime()));
        timeStats.sort(null);
        if (timeStats.size() > TOP_NUM) { //截断多余的,仅保留TOP_NUM个sql
            timeStats.remove(TOP_NUM);
        }
    }




    //合并多个统计信息
    @Override
    public void combine(List<Statictics> multiStats) {
        timeStats.clear();
        for (Statictics stat : multiStats) {
            timeStats.addAll(((StatExecTime) stat).timeStats);
        }
        timeStats.sort(null);
    }

    //输出统计信息至文件
    @Override
    public void output(SqlLog log) {
        StringBuilder tmp = new StringBuilder();
        for (int i = 0; i < timeStats.size(); i++) {
            tmp.append(String.format("%s|%s\n", Utility.execMsToS(timeStats.get(i).time), timeStats.get(i).sql));
        }
        log.sqlLogMessage(tmp.toString());
        log.Flush();
    }
}